package com.easypan.Service.impl;

import com.easypan.Service.EmailCodeService;
import com.easypan.Service.UserService;
import com.easypan.entity.constants.Constants;
import com.easypan.entity.po.MailRequest;
import com.easypan.entity.po.email;
import com.easypan.entity.vo.R;
import com.easypan.mapper.EmailMapper;
import com.easypan.mapper.UserMapper;
import com.easypan.util.SendMailService;
import com.easypan.util.StringTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class EmailCodeservice implements EmailCodeService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmailMapper emailMapper;
    @Autowired
    private SendMailService sendMailService;
    @Override
    @Transactional
    public R sendEmail(String email, String type, HttpServletRequest request) {
     if(type.equals(Constants.ZERO))
     {
         //注册 --先查看数据库是否有重复邮箱
         int count = userMapper.selectByEmail(email);
          if(count!=0)
          {
              return R.error("该邮箱已经注册");
          }
     }
     //新
        //1.生成随机数
        String randomNumber = StringTools.getRandomNumber(4);
        ///2.发送邮箱

        //3.往数据库塞值
        //逻辑1 用户有可能会往数据库再次塞值 --每次都需要将相同邮箱的所有验证码 给予已使用
        String clientip = request.getRemoteAddr();
        //记录一下IP 后续 用redis 或者seionn来控制对方访问该数据库的频率 防止刷爆sql语句
       emailMapper.disableEmailCode(email);
       email emaila=new email();
        emaila.setCode(randomNumber);
        emaila.setEmail(email);
        emaila.setStatus(0);
        emaila.setCreateTime(new Date());
        emailMapper.insert(emaila);

//------邮箱内容构造
        MailRequest mailRequest=new MailRequest();
        mailRequest.setSendTo(email);
        mailRequest.setSubject("easyPan 验证码");
        mailRequest.setText("你的四位验证码为"+randomNumber+"验证码永远不会失效，除非有新的验证码到来");
        sendMailService.sendSimpleMail(mailRequest);
        return R.success("成功");
    }


}
